import wsgiref.handlers
import os
import datetime
import logging
import time
from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext import db
from pytz import timezone
import models, utils, datastore, charts, devhandlers

class MainPage(webapp.RequestHandler):
  def get(self):
    url = 'http://upload.wikimedia.org/wikipedia/commons/thumb/e/e9/Sad_face.svg/603px-Sad_face.svg.png'
    system = self.request.get('system')
    hours = int(self.request.get('hours','18'))
    if system == None or system == '':
      array = models.SolarArray.all().fetch(1)[0]
    else:
      key = db.Key(system)
      array = models.SolarArray.get(key)
    tz = array.tz
    if tz == None:
      tz = 'US/Pacific'
    data = models.SolarData.all()
    data.filter('system =',array.key())
    data.order('-date')
    latest = data.fetch(1)[0]
    now = utils.roundDt(utils.toTZ(datetime.datetime.now(), tz)) - datastore.INTERVAL_DELTA
    delta = datetime.timedelta(hours=hours)
    start = now - delta
    points = hours * 4 
    today = now.date()
    maxWattsToday = 0
    localCutoff = datetime.time(9, tzinfo = timezone(tz))
    agg = datastore.getAggregates(array, now, start, points, tz)
    times = []
    totals = []

    for d in agg:
      dateTz = utils.toTZ(d.date, tz)
      times.insert(0, dateTz)
      totals.insert(0, d.watts)
      if dateTz.date() == today and d.maxWatts > maxWattsToday:
        maxWattsToday = d.watts

    #logging.debug(totals)
    days = [ today - datetime.timedelta(days = x) for x in xrange(6,0,-1)]
    kwhNow, kwhTotal = datastore.getDayInfo(array, days, now)
    
    #add today
    days.append(today)
    kwhTotal.append(agg[0].kwhToday)
    kwhNow.append(agg[0].kwhToday)
    maxKwh = max(kwhTotal)
    chart = charts.plotSolarDay(times, totals)
    
    dayLabels = [day.strftime("%m-%d") for day in days]
    totalChart = charts.barChart(dayLabels, 'kWh Total', kwhTotal, maxKwh)
    label = 'kWh at ' + now.strftime("%I:%M%p")
    soFarChart = charts.barChart(dayLabels,
      label, kwhNow, maxKwh)
    url = chart.get_url()
    renderToTemplate(self, 'index.html', {'url' : url,
                                        'now' :  now.strftime('%I:%M%p %m-%d-%y'),
                                        'total_url' : totalChart.get_url(),
                                        'soFar_url' : soFarChart.get_url(),
                                        'latest' : latest,
                                        'readout' : (
                                                     ('Last Sample:', utils.toTZ(latest.date,tz).strftime('%I:%M%p %m-%d-%y')),
                                                     ('Watts', latest.watts),
                                                     ('kWh Today', latest.kwhToday),
                                                     ('kwh Lifetime', latest.kwhLifetime),
                                                     ('Max Watts Today', latest.watts > maxWattsToday and latest.watts or maxWattsToday),
                                                     ("Carbon Dioxide Saved", "%.2f pounds" % (latest.kwhLifetime*0.81)),  #810 lbs co2 per 1000 kwh, according to terrpass
                                                    ),
                                        'system' : system
                                       })


   

  
class SolarArrays(webapp.RequestHandler):
  def get(self):
    arrays = models.SolarArray.all()
    renderToTemplate(self, 'arrays.html', { 'arrays' : arrays})
  def post(self):
    array = models.SolarArray()
    array.owner = self.request.get('owner')
    array.put()
    self.redirect('/arrays')

class SubmitData(webapp.RequestHandler):
  def get(self):
    self.post()
  
  def post(self):
    system = self.request.get('system')
    key = db.Key(system)
    array = models.SolarArray.get(key)
    data = models.SolarData(system = array.key())
    data.watts = int(self.request.get('watts'))
    data.kwhToday = float(self.request.get('kwhToday'))
    data.kwhLifetime = float(self.request.get('kwhLifetime'))
    time = self.request.get('date')
    if time != None and time != '':
      data.date = datetime.datetime.utcfromtimestamp(int(time))
    data.put()
    #self.redirect('/?system=' + self.request.get('system'))


    
def renderToTemplate(handler, name, values):
  name = os.path.join(os.path.dirname(__file__), name)
  handler.response.headers['Content-Type'] = 'text/html'
  handler.response.out.write(template.render(name, values))

class Dump(webapp.RequestHandler):
    def get(self):
      self.response.headers['Content-Type'] = 'text/plain'
      system = self.request.get('system')
      key = db.Key(system)
      array = models.SolarArray.get(key)
      day = int(self.request.get('day'))
      month = int(self.request.get('month'))
      year = int(self.request.get('year'))
      begin = datetime.datetime(year, month, day, 0, 0, 0)
      end = datetime.datetime(year, month, day, 23, 59, 59)
      data = models.SolarData.all().filter('system =', array.key()).filter('date >', begin).filter('date <', end)
      for d in data:
        self.response.out.write('%d,%d,%f,%f\n' % (time.mktime(d.date.utctimetuple()), d.watts, d.kwhToday, d.kwhLifetime))

def main():
  debug = False
  handlers = [('/', MainPage), 
              ('/arrays', SolarArrays), 
              ('/submit', SubmitData),
              ('/dump', Dump)]
  if os.environ["SERVER_SOFTWARE"] == 'Development/1.0':
    debug = True
    handlers += [('/populate', devhandlers.Populate),
                 ('/clean', devhandlers.CleanAggregates),
                 ('/clone', devhandlers.Clone)]
  application = webapp.WSGIApplication(handlers,
                                       debug = debug)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()